package com.example.wxai.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtlis {
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5tQ4tLPyjxQx5tCmxViH";
    private String accessKeySecret = "zKzZUNwnjX2y9aGcXtKqVcV2hElANT";
    CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
    private  String bucketName = "baibaiyu-shopping";

    public String upload(MultipartFile file) throws Exception{
        InputStream inputStream=file.getInputStream();
        //避免文件覆盖
        String orFileName=file.getOriginalFilename();
        String filename= UUID.randomUUID().toString()+orFileName.substring(orFileName.lastIndexOf("."));

        //上传文件到oss
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        ossClient.putObject(bucketName,filename,inputStream);

        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+filename;
        ossClient.shutdown();
        return url;
    }
}
